package com.iwinding.ladygg.ui.act;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.iwinding.ladygg.R;
import com.iwinding.ladygg.constant.SPConstant;
import com.iwinding.ladygg.net.RequestManager;
import com.iwinding.ladygg.net.callback.BaseRpCallback;
import com.iwinding.ladygg.net.callback.HeadImgCallback;
import com.iwinding.ladygg.net.callback.PersonInfoCallback;
import com.iwinding.ladygg.net.request.UpdatePersonInfoReq;
import com.iwinding.ladygg.net.response.BaseRopnse;
import com.iwinding.ladygg.net.response.HeadImgRp;
import com.iwinding.ladygg.net.response.LoginRp;
import com.iwinding.ladygg.net.response.PersonInfoRp;
import com.iwinding.ladygg.ui.view.ProDialogCreator;
import com.iwinding.ladygg.utils.GsonUtil;
import com.iwinding.ladygg.utils.SPUtils;
import com.iwinding.ladygg.utils.SystemUtil;
import com.iwinding.ladygg.utils.ToastUtil;

import java.util.ArrayList;

/**
 * 我的信息界面
 * Created by hezhiyong on 2017/3/14.
 */

public class InfoActivity extends BaseActivity implements View.OnClickListener {

    private final static int UPDATE_NAME = 100;
    private final static int UPLOAD_PHOTO = 101;
    private final static int SELECT_SEX = 102;
    private final static int SELECT_AGE = 103;

    private SimpleDraweeView draweeView;
    private TextView mTvName;
    private TextView mTvID;
    private TextView mTvSex;
    private TextView mTvAge;

    private PersonInfoRp personInfo;
    private String path = "";

    @Override
    protected int getLayoutID() {
        return R.layout.icane_activity_personal_info;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ProDialogCreator.getInstance().initContext(this);
        initView();
        reqestInfo();
    }

    void initView() {
        setBackTxtResId(R.string.bottom_tab_myself);
        setTitleResId(R.string.icane_my_personal_info);
        setRightTxtResId(R.string.icane_save);


        mRightTxt.setOnClickListener(saveOnclick);

        findViewById(R.id.lay_my_head_portrait).setOnClickListener(this);
        findViewById(R.id.lay_my_name).setOnClickListener(this);
        findViewById(R.id.lay_my_account_number).setOnClickListener(this);
        findViewById(R.id.lay_my_qrcode).setOnClickListener(this);
        findViewById(R.id.lay_my_sex).setOnClickListener(this);
        findViewById(R.id.lay_my_age).setOnClickListener(this);

//        Uri uri = Uri.parse("https://raw.githubusercontent.com/facebook/fresco/gh-pages/static/fresco-logo.png");
        draweeView = (SimpleDraweeView) findViewById(R.id.my_image_view);
//        draweeView.setImageURI(uri);

        mTvName = (TextView) findViewById(R.id.info_name);
        mTvID = (TextView) findViewById(R.id.info_id);
        mTvSex = (TextView) findViewById(R.id.info_sex);
        mTvAge = (TextView) findViewById(R.id.info_age);
    }

    /**
     * 请求网络数据 info信息
     */
    void reqestInfo() {
        RequestManager.postPersonInfo(mContext, new PersonInfoCallback() {
            @Override
            public void onResult(PersonInfoRp personInfoRp) {
                personInfo = personInfoRp;
                String sex = (personInfo.gender == 1 ? "男" : "女");
                SPUtils.putSpProperty(mContext, SPConstant.PERSONINFO, GsonUtil.getInstance().toJson(personInfo));

                String name = TextUtils.isEmpty(personInfo.nickName) ? (TextUtils.isEmpty(personInfo.name) ? "" : personInfo.name) : personInfo.nickName;
                if (TextUtils.isEmpty(name)) {
                    LoginRp loginRp = SystemUtil.getLoginRp(mContext);
                    name = loginRp.getName();
                }

                String id = TextUtils.isEmpty(personInfo.mobile) ? (TextUtils.isEmpty(personInfoRp.uname) ? "" : personInfoRp.uname) : personInfo.mobile;
                setInfo(personInfo.headImg, name, id, sex, String.valueOf(personInfoRp.age));
            }

            @Override
            public void onFail(String errorMsg) {
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
                finish();
            }
        });
    }

    /**
     * 设置基础信息
     *
     * @param imageUrl
     * @param name
     * @param id
     * @param sex
     * @param age
     */
    void setInfo(String imageUrl, String name, String id, String sex, String age) {
        if (!TextUtils.isEmpty(imageUrl)) {
            try {
                Uri uri = Uri.parse(imageUrl);
                draweeView.setImageURI(uri);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (!TextUtils.isEmpty(name)) {
            mTvName.setText(name);
        }
        if (!TextUtils.isEmpty(id)) {
            mTvID.setText(id);
        }
        if (!TextUtils.isEmpty(sex)) {
            mTvSex.setText(sex);
        }
        if (!TextUtils.isEmpty(age)) {
            if (TextUtils.equals(age, "0")) {
                age = "1";
            }
            mTvAge.setText(age);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_my_head_portrait:
                startActivityForResult(new Intent(this, SelectPicActivity.class), UPLOAD_PHOTO);
                break;
            case R.id.lay_my_name:
                Intent name = new Intent(this, NameActivity.class);
                name.putExtra(NameActivity.NAME, personInfo.name);
                startActivityForResult(name, UPDATE_NAME);
                break;
            case R.id.lay_my_account_number:
                break;
            case R.id.lay_my_qrcode:
                Intent qr = new Intent(this, QrcodeActivity.class);
                qr.putExtra(QrcodeActivity.LASTACTNAME, getString(R.string.icane_my_personal_info));
                startActivity(qr);
                break;
            case R.id.lay_my_sex:
                Intent sex = new Intent(this, WheelActivity.class);
                sex.putExtra(WheelActivity.WHEELSELECTSTR, mTvSex.getText().toString());
                ArrayList<String> data = new ArrayList<String>();
                data.add("男");
                data.add("女");
                sex.putStringArrayListExtra(WheelActivity.WHEELSELECTDATA, data);
                startActivityForResult(sex, SELECT_SEX);
                break;
            case R.id.lay_my_age:
                Intent age = new Intent(this, WheelActivity.class);
                age.putExtra(WheelActivity.WHEELSELECTSTR, mTvAge.getText().toString());
                ArrayList<String> ageData = new ArrayList<String>();
                for (int i = 1; i < 101; i++) {
                    ageData.add(String.valueOf(i));
                }
                age.putStringArrayListExtra(WheelActivity.WHEELSELECTDATA, ageData);
                startActivityForResult(age, SELECT_AGE);
                break;
        }
    }

    /**
     * 保存的逻辑处理
     */
    private View.OnClickListener saveOnclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (personInfo == null) {
                return;
            }
            if (TextUtils.isEmpty(path) && TextUtils.isEmpty(personInfo.headImg)) {
                ToastUtil.openBaseToast(mContext, R.string.icane_save_hint_headimg, Toast.LENGTH_SHORT);
                return;
            }
            uploadSave();
            SPUtils.putSpProperty(mContext, SPConstant.PERSONINFO, GsonUtil.getInstance().toJson(personInfo));
            setResult(RESULT_OK);
//            finish();
        }
    };

    /**
     * 上传保存
     */
    void uploadSave() {
        if (!TextUtils.isEmpty(path)) {
            updateImgAndInfo();
        } else {
            updateInfo(personInfo.headImg);
        }
    }

    private void updateImgAndInfo() {
        ProDialogCreator.getInstance().showDialog("正在上传...");
        RequestManager.postHeadImg(this, path, new HeadImgCallback() {
            @Override
            public void onResult(final HeadImgRp headImgRp) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateInfo(headImgRp.headImg);
                    }
                });
            }

            @Override
            public void onFail(String errorMsg) {
                ProDialogCreator.getInstance().dismissDialog();
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }

    private void updateInfo(String headImg) {
        personInfo.headImg = headImg;
        UpdatePersonInfoReq req = new UpdatePersonInfoReq();
        req.age = Integer.parseInt(mTvAge.getText().toString());
        req.name = mTvName.getText().toString();
        req.gender = TextUtils.equals(mTvSex.getText().toString(), "男") ? 1 : 2;
        req.headImg = headImg;
        RequestManager.postUpdatePersonInfo(mContext, req, new BaseRpCallback<BaseRopnse>() {
            @Override
            public BaseRopnse parseResponse(BaseRopnse response, int id) {
                return response;
            }

            @Override
            public void onResult(BaseRopnse o) {
                SPUtils.putSpProperty(mContext, SPConstant.PERSONINFO, GsonUtil.getInstance().toJson(personInfo));
                ProDialogCreator.getInstance().dismissDialog();
                ToastUtil.openBaseToast(mContext, R.string.icane_save_ok, Toast.LENGTH_SHORT);
            }

            @Override
            public void onFail(String errorMsg) {
                ProDialogCreator.getInstance().dismissDialog();
                ToastUtil.openBaseToast(mContext, errorMsg, Toast.LENGTH_SHORT);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case UPDATE_NAME:
                    String name = data.getStringExtra(NameActivity.NAME);
                    mTvName.setText(name);
                    personInfo.name = name;
                    break;
                case SELECT_SEX:
                    String sex = data.getStringExtra(WheelActivity.WHEELSELECTSTR);
                    mTvSex.setText(sex);
                    break;
                case SELECT_AGE:
                    String age = data.getStringExtra(WheelActivity.WHEELSELECTSTR);
                    mTvAge.setText(age);
                    break;
                case UPLOAD_PHOTO:
                    path = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
                    try {
                        Uri uri = Uri.parse("file:///" + path);
                        draweeView.setImageURI(uri);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }
}
